package com.bwstudio.demo.consumer.message;

import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;
import com.bwstudio.demo.consumer.message.template.MsgProcessTemplateV1;
import com.bwstudio.demo.consumer.model.AccountChangeEvent;
import com.bwstudio.demo.consumer.service.AccountInfoService;

import lombok.extern.slf4j.Slf4j;

@Component
@Slf4j
@RocketMQMessageListener(topic = "topic_txmsg", 
	selectorExpression = "v1",
	consumerGroup = "${spring.application.name}-txmsg-bank2-v1")
public class TxmsgConsumerV1 implements RocketMQListener<String> {

	@Autowired
    AccountInfoService accountInfoService;

    //接收消息
    @Override
    public void onMessage(String message) {
        new MsgProcessTemplateV1() {
        	
			@Override
			protected JSONObject doParse(String jsonStr)  {
				return  JSONObject.parseObject(jsonStr);
			}

			@Override
			protected void doValidateAndUpdateDB(JSONObject jsonObject) throws RuntimeException {
		        String accountChangeString = jsonObject.getString("accountChange");
		        //转成AccountChangeEvent
		        AccountChangeEvent accountChangeEvent = JSONObject.parseObject(accountChangeString, AccountChangeEvent.class);
		        if(!StringUtils.equals(accountChangeEvent.getAccountNo(), "2")) {
		        	throw new RuntimeException("转入bank2的账户不正确");
		        }
		        //更新本地账户，增加金额
		        accountInfoService.addAccountInfoBalance(accountChangeEvent);
			}
        	
        }.doProcess(message);

    }
}
